package com.promise.jokerdream.work.signin

import com.promise.jokerdream.manager.ExecutionHistoryManager
import com.promise.jokerdream.repository.GameApi
import com.promise.jokerdream.repository.foldWithApiException
import com.promise.jokerdream.response.pc.QueryWeeklyGiftResponse
import com.promise.jokerdream.utils.AppContext
import com.promise.jokerdream.work.BaseWork
import com.promise.jokerdream.work.WorkResult

// 周周礼包工作
class WeeklyGiftWork(uin: String): BaseWork(uin) {
    
    override val name: String
        get() = "周周礼包"

    override val isActWork: Boolean
        get() = true

    override val priority: Int
        get() = 8
    
    private val gameApi = GameApi.getInstance()
    private val historyManager by lazy { ExecutionHistoryManager.getInstance(AppContext.get()) }

    override suspend fun executeWork(): WorkResult {
        return try {
            // 1. 先查询周周礼包信息
            val queryResult = gameApi.queryWeeklyGift()
            queryResult.foldWithApiException(
                onSuccess = { response ->
                    processWeeklyGift(response)
                },
                onFailure = { code, msg ->
                    historyManager.addHistory(name, msg, code)
                    WorkResult.Failure(Exception(msg), msg)
                }
            )
        } catch (e: Exception) {
            historyManager.addHistory(name, e.message)
            WorkResult.Failure(e, e.message)
        }
    }

    /**
     * 处理周周礼包逻辑
     */
    private suspend fun processWeeklyGift(response: QueryWeeklyGiftResponse): WorkResult {
        // 检查packageList，找出isAwarded为0的礼包（未领取）
        val claimablePackages = response.packageList.filter { it.isAwarded == 0 }
        
        if (claimablePackages.isNotEmpty()) {
            // 有可领取的礼包，逐个领取
            for (packageItem in claimablePackages) {
                val claimResult = gameApi.claimWeeklyGift(packageItem.id)
                claimResult.foldWithApiException(
                    onSuccess = { claimResponse ->
                        historyManager.addHistory(name, "${packageItem.packageName}: ${claimResponse.getDescription()}")
                    },
                    onFailure = { code, msg ->
                        historyManager.addHistory(name, "${packageItem.packageName}: $msg", code)
                    }
                )
            }
        }
        
        return WorkResult.Success
    }
}